# -*- coding:utf-8 -*-
import requests
from django.core.cache import cache
import logging

logger = logging.getLogger('django')

# 企业ID
corp_id = 'wwe9f6a4e657c8bb09'
# 应用Secret
corp_secret = 'cb0eiGwQYjNbRPXtSVKICGH8VYjizlwrZcLr3FbhuSo'
# 通讯录同步Secret
contacts_secret = 'OcCMM9z-oNb5jm55UHPuvTeftqVCkD1DXQXD6V-zHAk'

Application_token = 'pEKPBTwXT-_9ToxsSUrcFxBN1L6V-hXeBHqTW58_tA_7i3WtZyh6lgWj3oGPd0qlecniiDFtgRbVcDsRM7CFDLxxQPbxgng1ImOs8NmVgzDZOkIpdK0JTNFGl7Z4YGwS3HW4JIu9h_Qz02DNkHff3EGczQOVdzopjjM33eOP_KWHBIljXf-k934HqX1WSAeCzHM0eI4Kyr3QFgngxwsY6w'


def getApplicationToken():
    """
    企业ID    wwe9f6a4e657c8bb09
    应用Secret    cb0eiGwQYjNbRPXtSVKICGH8VYjizlwrZcLr3FbhuSo

    {"errcode":0,"errmsg":"ok","access_token":"MXhiY1UNgwkvXM5i0zRhbS1jmuXBFFVhJpPMNZJVQ4Rj-A3HNuYp5tiWqb5oKkyV3Agb9008zU-PMLNYZCZwm92057jH5oLeL6egwqcW2PbwCrKO04hx3DIoQ_PLnGahydaGikRHYRCtCT9JGp-vqfkTl6Q0hIbIZawIbKeb70PZT26GMGnycboyUYKfP7QHq-5XX99Mg428OeZLhVBDpw","expires_in":7200}

    """
    # params = {"corpid": self._corpid, "corpsecret": "cb0eiGwQYjNbRPXtSVKICGH8VYjizlwrZcLr3FbhuSo"}
    params = {"corpid": corp_id, "corpsecret": corp_secret}
    url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
    response = requests.get(url=url, params=params)
    return response.json()


def getContactsToken():
    """
    通讯录同步
    可通过API接口或第三方应用同步通讯录
    通讯录同步Secret   OcCMM9z-oNb5jm55UHPuvTeftqVCkD1DXQXD6V-zHAk

    {"errcode":0,"errmsg":"ok","access_token":"MXhiY1UNgwkvXM5i0zRhbS1jmuXBFFVhJpPMNZJVQ4SZMNR52XZvkWoyGOQZmKmP1ZgllaK2hAPyY4YEtQASwmM_T0Diupd5dozT3hXR_l4bClB7c3C7FPxaQNjqe-1Mo-TYAvqvGrRbs1FiMwBs8tnRvheJzdYGYQUyq6tz-_j81em53mdsS-QPxOSPqiFHJz5Qrgu1Fe6-n4IghLYoBg","expires_in":7200}

    """

    # params = {"corpid": self._corpid, "corpsecret": "OcCMM9z-oNb5jm55UHPuvTeftqVCkD1DXQXD6V-zHAk"}
    params = {"corpid": corp_id, "corpsecret": contacts_secret}
    url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'

    response = requests.get(url=url, params=params)

    """
        数据同步
        可将企业使用的 Microsoft Active Directory 与 Exchange 的帐号、邮箱和日历数据统一迁移至企业微信并持续同步。
     """
    return response.json()


# 发送应用消息的装饰器
def try_send_Application_message(fun):
    def inner(*args):
        result = fun(*args)
        logger.info(f"第一次:{result['errcode']}")
        if result["errcode"] != 0:
            ApplicationResult = getApplicationToken()
            cache.set("Application_token", ApplicationResult["access_token"])
            result = fun(*args)
            logger.info(f"重新获取:{result['errcode']}")
        return result

    return inner


@try_send_Application_message
def sendText(content):
    """
    发送应用消息
    :return:
    """
    data = {
        "touser": "@all",
        "toparty": "",
        "totag": "",
        "msgtype": "text",
        "agentid": 1000002,
        "text": {
            "content": content
        },
        "safe": 0,
        "enable_id_trans": 0,
        "enable_duplicate_check": 0,
        "duplicate_check_interval": 1800
    }
    # access_token = Application_token
    access_token = cache.get("Application_token", None)

    url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"

    response = requests.post(url=url, json=data)
    # {"errcode": 40014, "errmsg": "invalid access_token"}
    return response.json()



